local CopyL = require("copy.CopyL")
local CopyDefine = require("copy.Define")
local ObjHuman = require("core.ObjHuman")
local Timer = require("core.Timer")
local Lang = require("common.Lang")
--local Util = require("common.Util")
local Broadcast = require("broadcast.Broadcast")
local FamilyHandler = require("family.HandlerL")
local SceneEvent = require("core.SceneEvent")
local FamilyExcel = require("excel.Family")
local FamilyOnHookConfig = FamilyExcel.onhookact[1]
local Msg = require("core.Msg")

ExpCalc = ExpCalc or {}
HeartBeatCount = HeartBeatCount or {}

function checkEnter(human)
    if human.familyUuid == "" then
        Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FAMILY_ALLY_NO_FAMILY)
        return false
    end

    if FamilyHandler.onGetOnHookLeftTime(human) <= 0 then
        Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FAMILY_ACT_ONHOOK_NOTIME)
        return false
    end

    return true
end

function onFamilyOnHookHumanEnterCopy(human, copyID, roomID)
    human.enterCopyTime = Timer.now
    for _, nSceneID in pairs(CopyL.copyList[copyID][roomID]) do
        local nAI = onGetDiffAI(human)
        SceneEvent.doSceneEvent(nSceneID, nAI)
        ExpCalc[roomID] = ExpCalc[roomID] or 0
        HeartBeatCount[roomID] = HeartBeatCount[roomID] or 0
    end
end

function onFamilyOnHookHumanLeaveCopy(human, copyID, roomID)
    FamilyHandler.onSendOnHookTime(human)
    ExpCalc[roomID] = nil
    HeartBeatCount[roomID] = nil
end

function onFamilyOnHookOneSec(copyID, roomID)
    HeartBeatCount[roomID] = (HeartBeatCount[roomID] or 0) + 1
    local nHumanList = CopyL.getCopyHumanList(copyID, roomID)
    for k, v in pairs(nHumanList) do
        v.db.familyOnHookTime = v.db.familyOnHookTime + 1
        local nRemainTime = FamilyHandler.onGetOnHookLeftTime(v)
        if nRemainTime <= 0 then
            CopyL.roomFinish(CopyDefine.COPY_FAMILY_ONHOOK_ID, roomID, CopyDefine.COPY_FINISH_ACT_END, "活动结束")
            CopyL.roomClear(copyID, roomID)
            ExpCalc[roomID] = nil
            HeartBeatCount[roomID] = nil
        else
            for _, nSceneID in pairs(CopyL.copyList[copyID][roomID]) do
                local nAI = onGetDiffAI(v)
                SceneEvent.doSceneEvent(nSceneID, nAI)
            end
            if HeartBeatCount[roomID] % 3 == 0 then
                onSendCopyData(v, roomID)
            end
        end
    end
end

function onGetDiffAI(human)
    local nLv = ObjHuman.getLv(human)
    local nAI = 0
    for k, v in ipairs(FamilyOnHookConfig.difficulty) do
        if v[1] <= nLv then
            nAI = v[2]
        end
    end
    return nAI
end

function onSendCopyData(human, roomID)
    local nSendMsg = Msg.gc.GC_COPY_FAMILYONHOOK_DATA
    nSendMsg.sumExp = ExpCalc[roomID] or 0
    Msg.send(nSendMsg, human.fd)
end

function onFamilyOnHookMonsterDie(killer, monster, monsterID, copyID, roomID, sumExp)
    ExpCalc[roomID] = (ExpCalc[roomID] or 0) + sumExp
end
